//
//  UITextViewScrollViewController.m
//  UITest
//
//  Created by wp w on 12-6-7.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "UITextViewScrollViewController.h"

@implementation UITextViewScrollViewController

UIScrollView *myScrollView;
UITextView *myTextView;

-(void)buttonClick:(id)sender
{
    [myTextView resignFirstResponder];
}

- (void)viewDidLoad {
	
	[super viewDidLoad];
	
    //新建scrollview的目的是，当键盘弹出时，尽量不遮挡editview
	CGRect viewRect = [self.view bounds];
	myScrollView = [[UIScrollView alloc] initWithFrame:viewRect];
	myScrollView.contentSize = viewRect.size;
    myScrollView.backgroundColor = [UIColor redColor];
	[self.view addSubview:myScrollView];
	
	CGRect buttonFrame = CGRectMake(10,10,60,32);
	UIButton *keyboardToggle = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[keyboardToggle setTitle:@"hide" forState:UIControlStateNormal];
	[keyboardToggle addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
	keyboardToggle.frame = buttonFrame;
	[myScrollView addSubview:keyboardToggle];
	
	CGRect textRect = CGRectMake(10,60,300,200);
	myTextView = [[UITextView alloc] initWithFrame:textRect];
	
	myTextView.font = [UIFont systemFontOfSize:22.0];
	
	myTextView.keyboardType = UIKeyboardTypeDefault;
	myTextView.returnKeyType = UIReturnKeyGo;
	
	//uncomment to enable data detectors
	//myTextView.text = @"this is a link: http://google.com ";
	//myTextView.dataDetectorTypes = UIDataDetectorTypeAll;
	//myTextView.enabled = NO;
	
	myTextView.delegate = self;
	
	[myScrollView addSubview:myTextView];
}

- (void)textViewDidBeginEditing:(UITextView *)textView 
{ 
	float keyboardHeight;
	if ([UIDevice currentDevice].orientation == UIDeviceOrientationPortrait ||
        [UIDevice currentDevice].orientation == UIDeviceOrientationPortraitUpsideDown )
		keyboardHeight = 216.0;
	else
		keyboardHeight = 162.0;
	
	CGRect textViewRect = textView.frame;
	float textViewBottom = textViewRect.origin.y + textViewRect.size.height;
	
	CGRect viewRect = [myScrollView bounds];
	float keyboardTop = viewRect.size.height-keyboardHeight;
//    float keyboardTop = textViewBottom+keyboardHeight;
	
	float scrollOffset = fabs(textViewBottom - keyboardTop);
	
	[myScrollView setContentOffset:CGPointMake(0, scrollOffset) animated:YES];  
}

- (void)textViewDidEndEditing:(UITextView *)textView 
{
	[myScrollView setContentOffset:CGPointMake(0, 0) animated:YES];  
}
- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [myTextView release];	
	[myScrollView release];
    
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}

@end
